<template>
  <div>
    <topbar></topbar>
    <div class="content">
      <div class="main">
        <el-upload
          class="avatar-uploader"
          action="#"
          :http-request="httpRequest"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <el-image v-if="this.imageUrl" :src="this.imageUrl" class="avatar" fit="cover" ></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >

          <el-form-item  prop="title">
            <el-input v-model="ruleForm.title" placeholder="标题" maxlength="30" show-word-limit></el-input>
          </el-form-item>

          <el-form-item prop="text">
            <el-input type="textarea" class="text-textarea" placeholder="若不填，将用标题作为一楼信息" v-model="ruleForm.text" :autosize="{ minRows: 8, maxRows: 20}" resize="none" maxlength="1500" show-word-limit></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading"
              >确认</el-button
            >
            <el-button @click="back()">返回文章页</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <footbar></footbar>
  </div>
</template>

<script>
import topbar from '../public/topbar.vue'
import footbar from '../public/footbar.vue'

export default {
  name: "writearticle",
  components: {
    footbar,
    topbar
  },
  data() {
    return {
      ruleForm: {
        title: "",
        text: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入标题"},
          {
            max: 30,
            message: "30个字符以内",
            trigger: "blur",
          },
        ],
        text: [{ message: "请输入一楼信息", trigger: "blur" }],
      },
      user: [],
      imageUrl: "",
      formData: {},
      file: {},
      loading: false
    }
  },
  mounted() {
    this.getUser(),
    this.setFormData()
  },
  methods: {
    getUser() {
      if(this.$cookies.isKey("CookieId")) {
        this.axios.get("http://www.liujn.top/bbs/api/user/seek/personal", { params: {
          username: this.$cookies.get("UserName")
        }}).then((res) => {
          this.user = res.data
          this.formData.append("username", this.user.username)
        })
      } else {
        this.$router.push("/article")
        this.$message.error("要写文章，请先登录~~")
      }
    },
    setFormData() {
      this.formData = new FormData()
    },
    back() {
      this.$router.go(-1)
    },
    beforeAvatarUpload(file) {
      let fileName = new Date().getTime().toString()
      console.log(file)
      if(file.type == "image/jpeg") {
        fileName = fileName + ".jpg"
      } else if (file.type == "image/png") {
        fileName = fileName + ".png"
      } else if (file.type == "image/gif") {
        fileName = fileName + ".gif"
      } else {
        fileName = fileName + ".???"
      }
      const copyFile = new File([file], fileName, {type: file.type})
      const isJPG = (copyFile.type === "image/jpeg") || (copyFile.type === "image/png") || (copyFile.type === "image/gif");
      const isLt2M = copyFile.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 、PNG 或 GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      this.file = copyFile
      return isJPG && isLt2M;
    },
    httpRequest (data) {
      let rd = new FileReader()
      let file = data.file
      rd.readAsDataURL(file)
      rd.onloadend = (e) => {
        this.imageUrl = e.target.result
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.file.name) {
            if(!this.ruleForm.text) { this.ruleForm.text = this.ruleForm.title}
            this.loading = true
            this.formData.append("image", this.file)
            this.formData.append("title", this.ruleForm.title)   
            this.formData.append("text", this.ruleForm.text)   
            this.axios.post('http://www.liujn.top/bbs/api/post/fatie', this.formData).then((res) => {
              if(res.data == 0) {
                this.$message({
                  type: "success",
                  message: "文章发送成功",
                  offset: 50
                }),
                this.$router.push('/article')
              } else {
                this.message.error("文章发送失败！")
              }
            })
          } else {
            this.$message.error("请上传主图~")
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
}
</script>

<style scoped lang="sass">

  .avatar-uploader .el-upload 
    border: 1px dashed #d9d9d9
    border-radius: 6px
    cursor: pointer
    position: relative
    overflow: hidden

  .avatar-uploader .el-upload:hover 
    border-color: #409eff

  .avatar-uploader-icon 
    font-size: 28px
    color: #8c939d
    width: 178px
    height: 178px
    line-height: 178px
    text-align: center

  .avatar 
    width: 178px
    height: 178px
    display: block


  .content
    width: 100%
    min-height: 90vh
    background-image: url("../../assets/bg9.jpg")
    background-size: 100% 100%
    background-size: 1920px 100%
    background-attachment: fixed
    background-repeat: no-repeat
    display: flex
    flex-direction: column
  

  .main 
    margin: 20px auto 20px auto
    width: 80%
    background-color: #fff
    padding: 20px
    
  .text-textarea
    padding: 0px 0px 45px 0px

  /deep/.is-success
    margin-bottom: 0px

  /deep/.el-textarea__inner
    text-align: justify
    line-height: 35px
    letter-spacing: 1px
    font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;


  @media screen and (max-width: 768px) 
    .main 
      margin: 20px auto 20px auto
      width: 85%
      background-color: #fff

</style>
